package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.Project;
import cn.bx.bid.service.ProjectService;
import cn.bx.bid.util.AjaxResult;
import cn.bx.bid.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class ProjectController {
    @Value("{uploadPath}")//spel
    private  String uploadPath;
    @Autowired
    ProjectService projectService;

  /*  @GetMapping("toAddProject")
    public String toAddProject(){
        return "projectAdd";
    }

    @PostMapping("addProject")
    public String addProject(HttpSession session, @ModelAttribute("p") Project project, @RequestParam(name = "fujian",required = false) MultipartFile file){
        LogUtil.info(">>>>>>>>>>>>>>>>>>>>file="+file);
        if (!(file.isEmpty()&&file==null)){
            String oldName = file.getOriginalFilename();
            String subfix = oldName.substring(oldName.indexOf("."));//截取上传文件拓展名
            String newName = UUID.randomUUID()+subfix;//生成新的文件名
            File dirPath = new File(session.getServletContext().getRealPath("doc"));//获得上下文路径的doc目录
            LogUtil.info(">>>>>>>>>>>>>>dirpath"+dirPath);
            if (!dirPath.exists()){
                dirPath.mkdirs();
            }
            try {
                file.transferTo(new File(dirPath,newName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            project.setProjectFilePath(newName);
        }
        LogUtil.info("project:"+project);
        projectService.add(project);
        return "addSuccess";
    }*/
    //掉渣
//    public String search(HttpServletResponse resp, @RequestParam(name = "page",defaultValue = "1") int pageNo, @RequestParam(name = "limit",defaultValue = "10")int limit){
//        Page<Project> paging = projectService.paging(pageNo, limit, null, null);
//        String jsonStr="";
//        resp.getWriter().print(jsonStr);
//        return null;
//    }
    @GetMapping(value = "projectsSearch",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Page<Project> paging(HttpServletResponse resp, @RequestParam(name = "page",defaultValue = "1") int pageNo,
                                @RequestParam(name = "limit",defaultValue = "10")int limit,
                                @RequestParam(name = "name",required = false)String name,
                                @RequestParam(name = "category",required = false)String category){
        Page<Project> paging = projectService.paging(pageNo,limit,name,category);
        return paging;
    }
//增加项目
@RequestMapping(value = "projectAdd",produces = "application/json;charset=utf-8")
@ResponseBody
public AjaxResult add(HttpSession s, @ModelAttribute("p") Project p, @RequestParam(name = "fujian", required = false) MultipartFile file, HttpServletRequest req) {
    LogUtil.info("哈哈哈哈哈---"+"存放在："+uploadPath);
    if (!(file == null || file.isEmpty())) {
        //文件后缀 getName()
        String oldName = file.getOriginalFilename();
        String prefix = oldName.substring(oldName.lastIndexOf('.'));
        //新文件名
        String newName = UUID.randomUUID() + prefix;
        //保存到项目的doc目录下
        //File path = new File(s.getServletContext().getRealPath("doc"));
        //放到指定目录
        File path = new File(uploadPath);
        LogUtil.info("文件的路径：" + path.getAbsolutePath());
        if (path.exists() == false)
            path.mkdirs();
        try {
            file.transferTo(new File(path, newName));
            p.setProjectFilePath(newName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    LogUtil.info("新项目的信息时：\n" + p);
    int add = projectService.add(p);

    if(add>0) {
        AjaxResult.success("msg","success");
    }
    return AjaxResult.error();
}

    //批量删除
    @GetMapping(value = "ProjectbatchDel",produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult batchDel(@RequestParam("ids[]") long[] ids){
        int r= this. projectService.batchDel(ids);
        if (r==1){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @InitBinder//影响一个controller
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值
    }
}